package com.discador.telein.data;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import java.util.List;

import com.discador.telein.model.Discador;

@ApplicationScoped
public class DiscadorRepository {

    @Inject
    private EntityManager em;

    public Discador findById(Long id) {
        return em.find(Discador.class, id);
    }

    public Discador findByEmail(String email) {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Discador> criteria = cb.createQuery(Discador.class);
        Root<Discador> discador = criteria.from(Discador.class);
        // Swap criteria statements if you would like to try out type-safe criteria queries, a new
        // feature in JPA 2.0
        // criteria.select(discador).where(cb.equal(discador.get(Discador_.name), email));
        criteria.select(discador).where(cb.equal(discador.get("email"), email));
        return em.createQuery(criteria).getSingleResult();
    }

    public List<Discador> findAllOrderedByName() {
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<Discador> criteria = cb.createQuery(Discador.class);
        Root<Discador> discador = criteria.from(Discador.class);
        // Swap criteria statements if you would like to try out type-safe criteria queries, a new
        // feature in JPA 2.0
        // criteria.select(discador).orderBy(cb.asc(discador.get(Discador_.name)));
        criteria.select(discador).orderBy(cb.asc(discador.get("name")));
        return em.createQuery(criteria).getResultList();
    }
}
